import * as EnumApi from "@/api/enum";
import { mapGetters } from "vuex";
import * as ExcelApi from "@/api/excel";
import * as UserApi from "@/api/user";
import * as UserEntityApi from "@/api/userEntity";
import * as UserGroupApi from "@/api/userGroup";
import * as CustomizeColumnApi from "@/api/customizeColumn";
import * as ResourceTypeApi from "@/api/resourceType";
import * as ResourceTypeFieldApi from "@/api/resourceTypeField";
import * as ResourceTypeEntityApi from "@/api/resourceTypeEntity";
import * as ResourceTypeEntityDataApi from "@/api/resourceTypeEntityData";
import { usingStatus } from "@/config/settings";

import SearchFormComponent from "@/views/pages/components/SearchFormComponent";
import ApplyInfoFormComponent from "@/views/pages/components/ApplyInfoForm";

export default {
  data() {
    return {
      // 资源类别信息
      resourceTypeInfo: {},
      name: "",

      // 实体字段列表
      resourceTypeEntityFieldList: [],
      isShow: true,

      // 实体使用状态
      usingStatus: [],

      // 待上传资源文件
      uploadFileList: [],
      // 上传文件弹窗显示
      uploadResourceFileDialogForm: false,
      // 多选选中行
      multipleSection: [],

      // 实体列表数据
      resourceTypeEntityDataList: [],
      // 资源实体查询条件
      queryParam: {},

      // 分页设置
      layout: "total, sizes, prev, pager, next, jumper",
      pageData: {
        currentPage: 1,
        pageSize: 20,
        total: 0,
      },

      // 控制添加资源实体弹窗出现消失
      addResourceEntityDialogForm: false,
      userList: [],

      // 弹窗标题
      title: "添加资源实体信息",

      // form表格label宽度
      formLabelWidth: "180px",

      // 添加的资源实体的数据
      addResourceEntityData: {},
      // 列表头信息
      headDatas: [],
      // 控制列头弹窗显示消失
      controlCustomizeColumnDialogForm: false,
      // 所有可选列头数据列表
      allCustomizeColumnList: [],
      // 选中的列头数据列表
      multipleSelectionColumnList: [],
      // 默认展示的列头信息
      defaultCustomizeColumnList: [],

      // 控制添加还是修改 true：添加，false：修改
      isAddData: true,

      // 控制添加申请窗口显示与消失
      addApplyDialogVisible: false,
      //当前是添加还是修改 true:添加;false:修改
      addOrUpdate: true,
      applyInfo: {},
    };
  },

  components: { SearchFormComponent, ApplyInfoFormComponent },

  inject: ["reload"],

  methods: {
    // 控制列头设置弹窗显示与消失
    handleControllerColumnsShow() {
      this.controlCustomizeColumnDialogForm = true;
      this.$nextTick(() => {
        this.defaultCustomizeColumnList.forEach((row, index) => {
          this.headDatas.forEach((selectedRow) => {
            if (row.label === selectedRow.label) {
              this.defaultCustomizeColumnList[index] = selectedRow;
              this.$refs.customizeColumnList.toggleRowSelection(
                this.defaultCustomizeColumnList[index],
                true
              );
            }
          });
        });
      });
    },
    // 弹出窗中表格多选框内容改变触发事件
    handleColumnSelectionChange(selection) {
      this.multipleSelectionColumnList = selection;
    },
    // 添加用户自定义列头
    handleUpdateCustomizeColumn() {
      let param = {
        username: this.userInfo.username,
        resourceType: this.name,
        columns: JSON.stringify(this.multipleSelectionColumnList),
      };
      CustomizeColumnApi.updateCustomizeColumn(param).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.reload();
        }
      });
    },
    handleDeleteCustomizeColumn() {
      let param = {
        username: this.userInfo.username,
        resourceType: this.name,
      };
      CustomizeColumnApi.deleteCustomizeColumn(param).then((res) => {
        if (res.code == 200) {
          this.$message.success("恢复默认显示成功");
          this.reload();
        }
      });
    },

    // 申请资源弹窗
    handleApplyInfo(index, row) {
      console.log(row);
      ResourceTypeEntityApi.getResourceTypeEntityByEntityId(
        row.resourceTypeEntityId
      ).then((res) => {
        if (res.data != null) {
          if (res.data.status != "free") {
            this.$message.error("该资源未处于空闲状态，不可申请");
          } else {
            this.$set(
              this.applyInfo,
              "applyResourceId",
              row.resourceTypeEntityId
            );
            this.$set(this.applyInfo, "resourceTypeName", row.resourceTypeName);
            this.addApplyDialogVisible = true;
          }
        }
      });
    },
    // 弹窗关闭
    closedDialog(dialogVisible) {
      this.addApplyDialogVisible = dialogVisible;
      this.addOrUpdate = true;
    },

    // 获取用户组列表
    getUserGroupList() {
      UserGroupApi.getUserGroupList().then((res) => {
        res.data.forEach((userGroup) => {
          let childrenUserLit = [];
          UserApi.getUserListByGroupName(userGroup.userGroupName).then(
            (res) => {
              res.data.forEach((user) => {
                childrenUserLit.push({
                  value: user.username,
                  label: user.realName,
                });
              });
            }
          );
          this.userList.push({
            value: userGroup.userGroupName,
            label: userGroup.userGroupName,
            children: childrenUserLit,
          });
        });
      });
    },

    // 获取资源类别英文名
    getResourceTypeName() {
      const path = this.$route.path;
      let resourceTypeName = path.substring(path.lastIndexOf("/") + 1);
      this.name = resourceTypeName;
      // 获取资源类别信息
      this.getResourceTypeInfo(resourceTypeName);
    },

    // 获取资源类别信息
    getResourceTypeInfo(resourceTypeName) {
      ResourceTypeApi.getResourceTypeByName(resourceTypeName).then((res) => {
        this.resourceTypeInfo = res.data;
        this.isShow = false;
        // 获取资源实体字段信息
        this.getResourceTypeEntityFieldList();
      });
    },

    // 获取资源类别实体字段列表
    getResourceTypeEntityFieldList() {
      ResourceTypeFieldApi.getResourceTypeFieldByName(
        this.resourceTypeInfo.resourceTypeName
      ).then((res) => {
        this.resourceTypeEntityFieldList = res.data;
        this.resourceTypeEntityFieldList.forEach((fieldInfo) => {
          if (fieldInfo.resourceTypeFieldType == "enum") {
            EnumApi.getEnumItemByGroupName(fieldInfo.enumGroupName).then(
              (res) => {
                this.$set(fieldInfo, "enumItemList", res.data);
              }
            );
          }
        });
        // 获取资源实体数据
        this.getResourceTypeEntityDataList();
        this.isShow = true;
      });
    },

    // 获取表格数据
    getResourceTypeEntityDataList() {
      this.queryParam = {
        resourceTypeName: this.resourceTypeInfo.resourceTypeName,
        currentPage: this.pageData.currentPage,
        pageSize: this.pageData.pageSize,
        queryEntityDtoList: [],
      };
      ResourceTypeEntityApi.queryResourceEntityPageList(this.queryParam).then(
        (res) => {
          this.resourceTypeEntityDataList = res.data.pageDataList;
          this.pageData.total = res.data.totalSize;
          // 获取资源实体动态字段数据
          this.getResourceTypeEntityFieldData();
        }
      );
    },

    // 获取资源实体动态字段数据
    getResourceTypeEntityFieldData() {
      this.resourceTypeEntityDataList.forEach((element) => {
        ResourceTypeEntityDataApi.getResourceTypeEntityDataByEntityId(
          element.resourceTypeEntityId
        ).then((res) => {
          res.data.forEach((value) => {
            this.$set(
              element,
              value.resourceTypeFieldName,
              value.resourceTypeEntityDataValue
            );
          });
        });

        UserEntityApi.getUserEntityByEntityId(
          element.resourceTypeEntityId
        ).then((res) => {
          this.$set(
            element,
            "owner",
            res.data == null ? "" : res.data.username
          );
        });
      });
    },

    queryEntityList(queryParam, isComponent) {
      if (isComponent) {
        this.pageData.currentPage = 1;
      }
      this.queryParam = {
        resourceTypeName: this.resourceTypeInfo.resourceTypeName,
        currentPage: this.pageData.currentPage,
        pageSize: this.pageData.pageSize,
        queryEntityDtoList: queryParam.queryEntityDtoList,
      };
      ResourceTypeEntityApi.queryResourceEntityPageList(this.queryParam).then(
        (res) => {
          this.resourceTypeEntityDataList = res.data.pageDataList;
          this.pageData.total = res.data.totalSize;
          // 获取资源实体动态字段数据
          this.getResourceTypeEntityFieldData();
        }
      );
    },

    // 弹窗关闭时重置数据
    resetAddResourceEntityData() {
      this.addResourceEntityData = {};
    },

    // 格式化资源类别
    formatterResourceTypeName(val) {
      if (val.resourceTypeName === this.resourceTypeInfo.resourceTypeName) {
        return this.resourceTypeInfo.resourceTypeTitle;
      } else {
        return val.resourceTypeName;
      }
    },

    // 格式化时间
    formatterTime(row, column, cellValue, index) {
      return cellValue.substring(0, cellValue.lastIndexOf("."));
    },

    // 格式化状态
    formatterStatus(row, column, cellValue, index) {
      let stat = cellValue;
      this.usingStatus.forEach((status) => {
        if (status.key == cellValue) {
          stat = status.value;
        }
      });
      return stat;
    },
    // 格式化是否可申请
    formatterMayApply(row, column, cellValue, index) {
      let apply = "否";
      if (cellValue) {
        apply = "是";
      }
      return apply;
    },
    formatterNothing(row, column, cellValue, index) {
      return cellValue;
    },

    // 当前页发生改变
    handleCurrentChange(val) {
      this.pageData.currentPage = val;
      this.queryEntityList(this.queryParam, false);
    },
    // 当前页大小发生改变
    handleSizeChange(val) {
      this.pageData.currentPage = 1;
      this.pageData.pageSize = val;
      this.queryEntityList(this.queryParam, false);
    },

    // 搜索全部空闲资源
    searchAllFreeResource() {
      let param = {
        queryEntityDtoList: [
          {
            fieldName: "status",
            fieldValue: "free",
            fieldType: "enum",
            dynamics: false,
            tableName: "resource_type_entity",
          },
        ],
      };
      this.pageData.currentPage = 1;
      this.queryEntityList(param, false);
    },

    // 搜索全部可申请资源
    searchAllCouldApplyResource() {
      let param = {
        queryEntityDtoList: [
          {
            fieldName: "mayApply",
            fieldValue: "true",
            fieldType: "enum",
            dynamics: false,
            tableName: "resource_type_entity",
          },
        ],
      };
      this.pageData.currentPage = 1;
      this.queryEntityList(param, false);
    },

    // 点击添加资源实体按钮触发事件
    handleAddResourceEntity() {
      this.addResourceEntityDialogForm = true;
      this.isAddData = true;
      this.title = "添加资源实体信息";
      this.addResourceEntityData.resourceTypeTitle = this.resourceTypeInfo.resourceTypeTitle;
    },

    // 添加资源实体信息方法
    handleAdd() {
      if (this.isAddData) {
        this.handleAddResourceEntityData();
      } else {
        this.handleEditResourceEntityData();
      }
    },

    // 添加资源实体
    handleAddResourceEntityData() {
      this.$refs.addResourceEntityData.validate((valid) => {
        if (valid) {
          let entityData = {
            resourceTypeName: this.resourceTypeInfo.resourceTypeName,
            resourceTypeEntityDescription: this.addResourceEntityData
              .resourceTypeEntityDescription,
            status: this.addResourceEntityData.status,
          };
          ResourceTypeEntityApi.addResourceTypeEntity(entityData).then(
            (res) => {
              if (res.data != null) {
                this.getResourceTypeInfo(
                  this.resourceTypeInfo.resourceTypeName
                );
                this.handleAddResourceEntityFieldData(
                  res.data.resourceTypeEntityId
                );
              }
            }
          );
        }
      });
    },

    // 添加资源实体字段值
    handleAddResourceEntityFieldData(entityId) {
      let entityFieldValue = {
        resourceTypeName: this.resourceTypeInfo.resourceTypeName,
        resourceTypeEntityId: entityId,
      };
      let needToUpdateFieldNum = this.resourceTypeEntityFieldList.length;
      let handledNum = 0;
      this.resourceTypeEntityFieldList.forEach((element) => {
        const fieldName = element.resourceTypeFieldName;
        entityFieldValue.resourceTypeFieldName = fieldName;
        entityFieldValue.resourceTypeEntityDataValue = this.addResourceEntityData[
          fieldName
        ];
        ResourceTypeEntityDataApi.addResourceTypeEntityData(
          entityFieldValue
        ).then((res) => {
          handledNum++;
          if (handledNum == needToUpdateFieldNum) {
            if (this.addResourceEntityData.owner.length > 0) {
              this.updateUserEntityRelation(entityId);
            }
            this.$message.success("添加成功");
            this.addResourceEntityDialogForm = false;
          }
        });
      });
    },

    // 点击编辑按钮触发方法
    handleEditInfo(index, row) {
      this.addResourceEntityData = JSON.parse(JSON.stringify(row));
      this.addResourceEntityData.resourceTypeTitle = this.resourceTypeInfo.resourceTypeTitle;
      this.getUsernameByRealName(row.owner);
      this.addResourceEntityDialogForm = true;
      this.isAddData = false;
      this.title = "修改资源实体信息";
    },

    // 通过用户真实名获取到用户名
    getUsernameByRealName(realName) {
      this.userList.forEach((userGroup) => {
        userGroup.children.forEach((user) => {
          if (user.label == realName) {
            this.addResourceEntityData.owner = [userGroup.value, user.value];
          }
        });
      });
    },

    // 解决输入框无法输入
    change(e) {
      this.$forceUpdate();
    },

    // 修改资源类别实体信息
    handleEditResourceEntityData() {
      ResourceTypeEntityApi.updateResourceTypeEntityByEntityId(
        this.addResourceEntityData
      ).then((res) => {
        let entityFieldValue = {
          resourceTypeEntityId: this.addResourceEntityData.resourceTypeEntityId,
          resourceTypeName: this.resourceTypeInfo.resourceTypeName,
        };
        let needToUpdateFieldNum = this.resourceTypeEntityFieldList.length;
        let handledNum = 0;
        this.resourceTypeEntityFieldList.forEach((element) => {
          const fieldName = element.resourceTypeFieldName;
          entityFieldValue.resourceTypeFieldName = fieldName;
          entityFieldValue.resourceTypeEntityDataValue = this.addResourceEntityData[
            fieldName
          ];
          ResourceTypeEntityDataApi.updateResourceTypeEntityDataByEntityIdAndFieldName(
            entityFieldValue
          ).then((res) => {
            handledNum++;
            if (handledNum == needToUpdateFieldNum) {
              if (this.addResourceEntityData.owner.length > 0) {
                this.updateUserEntityRelation(
                  this.addResourceEntityData.resourceTypeEntityId
                );
              }
              this.getResourceTypeInfo(this.resourceTypeInfo.resourceTypeName);
              this.$message.success("修改成功");
              this.addResourceEntityDialogForm = false;
            }
          });
        });
      });
    },

    // 更新用户实体关系
    updateUserEntityRelation(entityId) {
      let userEntity = {
        entityId: entityId,
        userGroupName: this.addResourceEntityData.owner[0],
        username: this.addResourceEntityData.owner[1],
      };
      UserEntityApi.updateUserEntityByEntityId(userEntity).then((res) => {
        this.addResourceEntityData.owner = [];
      });
    },

    // 删除实体方法
    handleDeleteEntity(index, row) {
      ResourceTypeEntityApi.markDeleteResourceTypeEntityByEntityId(
        row.resourceTypeEntityId
      ).then((res) => {
        if (res.code == 200) {
          this.$message.success("删除成功");
          this.getResourceTypeInfo(this.resourceTypeInfo.resourceTypeName);
        } else {
          this.$message.error(res.message);
        }
      });
    },

    // 下载导入数据模板
    handleDownloadMoudle() {
      ExcelApi.downloadTemplate(this.resourceTypeInfo.resourceTypeName).then(
        (res) => {
          this.downloadFile(res);
        }
      );
    },

    // 重置上传文件列表
    resetUploadFileList() {
      this.uploadFileList = [];
    },
    // 点击叉号触发事件
    handleRemove(file, fileList) {
      this.uploadFileList = [];
    },
    // 点击提交触发事件
    submitUpload() {
      if (this.uploadFileList.length != 0) {
        this.$refs.upload.submit();
      } else {
        this.$message.error("请先选择文件!");
      }
    },
    // 上传前触发的函数
    beforeUpload(file) {
      // xls === application/vnd.ms-excel
      // xlsx = application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
      const isExcel =
        file.type ===
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      if (!isExcel) {
        this.$message.error("上传资源只能是 xlsx 格式!");
        return false;
      } else {
        return true;
      }
    },
    // 选择文件改变时触发的函数
    handleChange(file, fileList) {
      this.uploadFileList = [fileList[fileList.length - 1]];
    },

    // 上传文件
    uploadSectionFile(param) {
      // FormData 对象
      let form = new FormData();
      // 文件对象
      form.append("file", param.file);

      const loading = this.$loading({
        lock: true,
        text: "努力上传中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });

      ExcelApi.importResourceData(form).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.uploadResourceFileDialogForm = false;
          this.getResourceTypeEntityDataList();
        } else {
          loading.close();
          this.$message.error(res.message);
        }
        loading.close();
      });
    },

    // 导出文件
    handleDownloaResourceData() {
      ExcelApi.downloadResourceData(
        this.resourceTypeInfo.resourceTypeName
      ).then((res) => {
        this.downloadFile(res);
      });
    },

    // 导出选中数据
    handleDownloaSelectedResourceData() {
      if (this.multipleSection.length <= 0) {
        this.$message.warning("请至少选择一个实体！");
        return;
      }
      let entityListDto = {
        resourceTypeEntityList: this.multipleSection,
      };
      ExcelApi.downloadSelectedResourceData(entityListDto).then((res) => {
        this.downloadFile(res);
      });
    },

    // 下载文件
    downloadFile(res) {
      let blob = new Blob([res], {
        type:
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });
      let url = window.URL.createObjectURL(blob);
      let a = document.createElement("a");
      a.href = url;
      a.download = this.resourceTypeInfo.resourceTypeTitle + ".xlsx";
      a.click();
      window.URL.revokeObjectURL(url);
    },

    // 多选项
    handleSelectionChange(val) {
      this.multipleSection = val;
    },

    // 设置表格样式
    getHeadClass({ rowIndex }) {
      if (rowIndex == 0) {
        return "background-color:#ccc;color:#fff;font-size:30px;";
      }
    },
    getRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 !== 0) {
        return "warning-row";
      }
    },

    // 获取用户自定义列头显示
    getUserCustomizeColumn() {
      CustomizeColumnApi.getCustomizeColumn(
        this.userInfo.username,
        this.name
      ).then((res) => {
        this.headDatas = res.data;
      });
    },
    // 获取默认列头信息
    getDefaultCustomizeColumn() {
      CustomizeColumnApi.getCustomizeColumn("default", this.name).then(
        (res) => {
          this.defaultCustomizeColumnList = res.data;
        }
      );
    },
  },

  computed: {
    ...mapGetters({
      permissions: "user/permissions",
      userInfo: "user/userInfo",
    }),
  },
  created() {
    this.getResourceTypeName();
    this.getUserCustomizeColumn();
    this.getDefaultCustomizeColumn();
  },

  mounted() {
    this.usingStatus = usingStatus;
    this.getUserGroupList();
  },
};
